package com.fqxiny.picture.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.fqxiny.picture.common.exception.ErrorCode;
import com.fqxiny.picture.common.exception.ThrowUtils;
import com.fqxiny.picture.custom.manager.upload.PictureUploadTemplate;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.List;

@Service
public class UrlPictureUpload extends PictureUploadTemplate {
    @Override
    protected void validPicture(Object inputSource) throws MalformedURLException {
        String fileUrl = (String) inputSource;
        ThrowUtils.throwIf(StrUtil.isBlank(fileUrl), ErrorCode.PARAMS_ERROR, "文件地址不能为空");
        // 1. 校验文件大小
        try {
            long fileSize = getFileSizeFromUrl(fileUrl);
            final long MAX_FILE_SIZE = 5 * 1024 * 1024L;
            ThrowUtils.throwIf(fileSize > MAX_FILE_SIZE, ErrorCode.PARAMS_ERROR, "文件大小不能超过 5M");
        } catch (IOException e) {
            ThrowUtils.throwIf(true, ErrorCode.PARAMS_ERROR, "无法获取文件大小，请检查文件地址有效性");
        }

        // 2. 校验文件后缀
        String fileSuffix = getFileSuffixFromUrl(fileUrl);
        final List<String> ALLOWED_FORMATS = Arrays.asList("jpeg", "jpg", "png", "webp");
        ThrowUtils.throwIf(
                StrUtil.isBlank(fileSuffix) || !ALLOWED_FORMATS.contains(fileSuffix.toLowerCase()),
                ErrorCode.PARAMS_ERROR,
                "文件类型错误，仅支持 " + String.join(", ", ALLOWED_FORMATS)
        );
    }

    /**
     * 通过 HTTP HEAD 请求获取文件大小
     */
    private long getFileSizeFromUrl(String url) throws IOException {
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setRequestMethod("HEAD");
        int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            return connection.getContentLengthLong();
        } else {
            throw new IOException("HTTP Error: " + responseCode);
        }
    }

    /**
     * 从 URL 提取文件后缀（忽略大小写）
     */
    private String getFileSuffixFromUrl(String url) throws MalformedURLException {
        String path = new URL(url).getPath();
        String fileName = path.substring(path.lastIndexOf('/') + 1);
        return FileUtil.getSuffix(fileName);
    }
  
    @Override  
    protected String getOriginFilename(Object inputSource) {  
        String fileUrl = (String) inputSource;  
        // 从 URL 中提取文件名  
        return FileUtil.mainName(fileUrl);
    }  
  
    @Override  
    protected void processFile(Object inputSource, File file) throws Exception {
        String fileUrl = (String) inputSource;  
        // 下载文件到临时目录  
        HttpUtil.downloadFile(fileUrl, file);
    }  
}
